package com.fy56.platform.logistics.restful.api.controller.wx;


import com.alibaba.fastjson.JSONObject;
import com.fy56.platform.logistics.restful.api.utils.AlipayUtil;
import com.fy56.platform.logistics.utils.HttpClientUtils;
import com.fy56.platform.logistics.utils.StringUtil;
import com.google.common.collect.Maps;
import com.wordnik.swagger.annotations.Api;
import com.zeus.base.privilege.utils.ResultModel;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * 小程序支付Controller控制器
 *
 * @author zhaoyf
 * @version 2021-03-17
 */
@Api(value = "MiniPay", description = "小程序支付控制器", produces = MediaType.APPLICATION_JSON_VALUE)
@RestController
@RequestMapping("/miniPay")
public class MiniPayController {

    private static Logger log = Logger.getLogger(MiniPayController.class);

    @Autowired
    private AlipayUtil alipayUtil;

    /**
     * 小程序统一下单支付接口
     * <p>
     * http://localhost:8080/logistics-restful-api-test/MiniPay/toPay
     *
     * @param openid 用户openid
     * @param appid 小程序appid
     * @param loginName app用户名
     * @param password  app密码
     * @param sources  支付方式{1支付宝, 2微信, 11支付宝APP, 12微信APP, 21支付宝小程序, 22微信小程序, 24招行一网通}
     * @param loginSn 登陆串号
     * @param appServiceType  业务类型1(物流算盘) 2:新app用户购买
     * @param consumeTypeCode 消费项目
     * @param insuranceCodeId 保险险种， 消费项目不是保险 不必填
     * @param money  金额
     * @param appServicePriceId  服务时间价格表ID
     *
     */
    @RequestMapping(value = "/toPay", method = RequestMethod.GET)
    public ResultModel toPay(@RequestParam String openid, @RequestParam String appid,
                             @RequestParam String loginName, @RequestParam String password, @RequestParam String sources,
                             @RequestParam(required = false) String loginSn, @RequestParam(required = false) String appServiceType,
                             @RequestParam String consumeTypeCode, @RequestParam(required = false) String insuranceCodeId,
                             @RequestParam String money, @RequestParam(required = false) String appServicePriceId
    ) {
        ResultModel rs = new ResultModel(true, "发起支付成功");
        Map<String, String> postParams = Maps.newHashMap();
        Map<String, String> extraParam = Maps.newHashMap();
        String url = "";
        // 请求易宝支付所需要的的参数
        extraParam.put("openId", openid); //微信用户openid
        extraParam.put("appId",  appid); //appid
        if(!StringUtil.isEmpty(insuranceCodeId)){
            extraParam.put("insuranceCodeId",  insuranceCodeId); //保getOrderInfo险险种， 消费项目不是保险 不必填
        }
        postParams.put("loginName",loginName); //用户名
        postParams.put("password",password); //密码
        postParams.put("money", money);//充值金额
        if("服务费".equals(consumeTypeCode)){
            url = alipayUtil.getTyPayUrl();
            if(StringUtil.isEmpty(loginSn)){
                return new ResultModel(false, "登录串号(loginSn)不能为空");
            }
            if(StringUtil.isEmpty(appServiceType)){
                return new ResultModel(false, "业务类型(appServiceType)不能为空");
            }
            if(StringUtil.isEmpty(appServicePriceId)){
                return new ResultModel(false, "服务时间价格表ID(appServicePriceId)不能为空");
            }
            postParams.put("loginSn",loginSn); //登录串号
            postParams.put("appServiceType",appServiceType); //业务类型1(物流算盘) 2:新app用户购买
            postParams.put("appServicePriceId",appServicePriceId); //服务时间价格表ID
            postParams.put("paySources",sources); //支付方式
        }else{
            url = alipayUtil.getYbPayUrl();
            postParams.put("consumeTypeCode",consumeTypeCode); //消费项目编码
            postParams.put("sources", sources); //支付方式
            postParams.put("payChannel","23"); //支付通道
        }

        postParams.put("extraParam",JSONObject.toJSONString(extraParam)); //其他参数
        System.out.println("postParams==" + postParams.toString());
        String result = "";
        try{
            result = HttpClientUtils.post(url, postParams, null, 60000, 60000);
        }catch (Exception e){
            log.error("请求易宝支付接口失败", e);
            return new ResultModel(false, "请求易宝支付接口失败");
        }
        SortedMap<String, String> signParams = new TreeMap<String, String>();
        JSONObject jsonObject = (JSONObject) JSONObject.parse(result);
        // 请求支付接口，并返回成功处理
        if(jsonObject.getBoolean("success")){
            JSONObject newJsonObject = (JSONObject) jsonObject.get("object");
            if("22".equals(sources)){
                JSONObject responseBodyJson = null;
                if("服务费".equals(consumeTypeCode)){
                    String wxPayMess = newJsonObject.getString("barCode");
                    responseBodyJson = (JSONObject) JSONObject.parse(wxPayMess);
                }else{
                    String wxPayMess = newJsonObject.getString("onLinePayResult");
                    JSONObject wxJsonObject = (JSONObject) JSONObject.parse(wxPayMess);
                    String responseBody = wxJsonObject.getString("responseBody");
                    responseBodyJson = (JSONObject) JSONObject.parse(responseBody);
                }
                System.out.println("responseBodyJson:::::::: " + responseBodyJson.toString());
                signParams.put("appId", responseBodyJson.getString("appId"));//app_id
                signParams.put("nonceStr", responseBodyJson.getString("nonceStr"));
                signParams.put("package", responseBodyJson.getString("package"));
                signParams.put("signType", responseBodyJson.getString("signType"));
                signParams.put("timeStamp", responseBodyJson.getString("timeStamp"));//北京时间时间戳
                signParams.put("paySign", responseBodyJson.getString("paySign"));
            }
            if("21".equals(sources)){
                if("服务费".equals(consumeTypeCode)){
                    signParams.put("responseBody", newJsonObject.getString("barCode"));//outTradeNo
                }else{
                    String wxPayMess = newJsonObject.getString("onLinePayResult");
                    JSONObject wxJsonObject = (JSONObject) JSONObject.parse(wxPayMess);
                    signParams.put("responseBody", wxJsonObject.getString("responseBody"));//outTradeNo
                }
            }
            rs.setObject(signParams);
            return rs;
        }else{
            //返回失败处理
            log.info("下单失败，失败原因："+ jsonObject.get("message"));
            return new ResultModel(false, "下单失败，失败原因："+ jsonObject.get("message"));
        }
    }

}